package cn.liyunqi.ttv.main;

import cn.liyunqi.core.util.StringUtil;
import cn.liyunqi.core.util.TimeUtil;
import cn.liyunqi.ttv.main.constant.Constants;
import cn.liyunqi.ttv.main.constant.VersionEnum;
import cn.liyunqi.ttv.main.controller.MainUIController;
import cn.liyunqi.ttv.main.localdb.ConfigHelper;
import cn.liyunqi.ttv.main.vo.UserPreference;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;

import java.net.URL;

public class StartApp extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception {

        ConfigHelper.createEmptyFiles();
        ConfigHelper.createKedaxunfeiFile();

        //是否自动清理30天前的数据
        UserPreference userPreference = ConfigHelper.getUserPreferenceByUserId(Constants.userId);
        if(!(userPreference != null && userPreference.getAutoDelHistory() != null && 0 == userPreference.getAutoDelHistory())){
            Long nowTime = TimeUtil.getTime();

            Long beforeTime = nowTime - new Long("2592000000");
            ConfigHelper.deleteHistoryByUserIdAndTime(Constants.userId,beforeTime);
        }
        //写入版本号
        ConfigHelper.updateValueByName("localversion",VersionEnum.LOCAL_VERSION.getVersion());

        URL url = Thread.currentThread().getContextClassLoader().getResource("fxml/MainUI.fxml");
        FXMLLoader fxmlLoader = new FXMLLoader(url);
        Parent root = fxmlLoader.load();
        primaryStage.setResizable(true);
        primaryStage.getIcons().add(new Image("icons/icon.png"));
        primaryStage.setTitle("LTTV");
        primaryStage.setScene(new Scene(root));
        primaryStage.show();

        MainUIController controller = fxmlLoader.getController();
        controller.setPrimaryStage(primaryStage);
    }
    public String start(Stage primaryStage,String userId,String mail,String token,Long limitTime) throws Exception {
        //校验判断
        if(StringUtil.isEmptyOrNull(userId)){
            return "程序异常";
        }
        if(StringUtil.isEmptyOrNull(token)){
            return "程序异常";
        }
        if(StringUtil.isEmptyOrNull(mail)){
            return "程序异常";
        }
        if(StringUtil.isEmptyOrNull(limitTime)){
            return "程序异常";
        }
        Constants.userId = userId;
        Constants.mail = mail;
        Constants.token = token;
        Constants.limitTime = limitTime;

        this.start(primaryStage);
        return null;
    }


}
